	.file "bubble.s"

	.section .data
	.align 4
	.type g_data, @object
	.size g_data, 40
g_data:
	.long 10, 3, 7, 4, 2, 8, 5, 1, 9, 6

	.section .rodata
.LC0:
	.string "%d  "
.LC1:
	.string "\n"

	.section .text
	.global main
	.type main, @function
main:
	pushq %rbp
	movq %rsp, %rbp
	subq $8, %rsp
	pushq %rbx
	pushq %r12
	pushq %r13
	
	leaq g_data(%rip), %rbx
	movq $0, %r12
	movl $10, %ecx
1:
	leaq .LC0(%rip), %rdi
	movl 0(%rbx, %r12, 4), %esi

	movq %rcx, %r13
	call printf@PLT
	movq %r13, %rcx
	incq %r12
	loopl 1b

	leaq .LC1(%rip), %rdi
	call printf@PLT

	movq $9, %rdx	#save the last element index which swap occured last time
	leaq g_data(%rip), %rsi
BubbleSortOuter:
	movq $0, %rdi	#if swap occured??
	movq $0, %rax
BubbleSortInner:
	movl 0(%rsi, %rax, 4), %r8d
	cmpl 4(%rsi, %rax, 4), %r8d
	jle SkipSwap
	xchgl %r8d, 4(%rsi, %rax, 4)
	movl %r8d, 0(%rsi, %rax, 4)
	movq $1, %rdi	#yes, swap occured!!!
	movq %rax, %r9	#save the elemnt index which swap occured this time
SkipSwap:
	incq %rax
	cmpq %rdx, %rax
	jl BubbleSortInner

	movq %r9, %rdx
	testq %rdi, %rdi
	jnz BubbleSortOuter

	leaq g_data(%rip), %rbx
	movq $0, %r12
	movl $10, %ecx
1:
	leaq .LC0(%rip), %rdi
	movl 0(%rbx, %r12, 4), %esi

	movq %rcx, %r13
	call printf@PLT
	movq %r13, %rcx
	incq %r12
	loopl 1b

	leaq .LC1(%rip), %rdi
	call printf@PLT

	popq %r13
	popq %r12
	popq %rbx
	leaveq
	retq
